package com.kaifamiao.demo.d0808;

public class Demo {

    public static void main(String[] args) {
        String str = "pwabwkew";
        int length = maxSubString(str);
        System.out.println(length);
    }

    /**
     * 找字符串的最长不重复子串
     *    子串： 字符串中一定范围的字符串
     * pwwkew   --> wke 3
     * @param str
     * @return
     */
    public static int maxSubString(String str){
        if (str == null && str.isEmpty()){
            return -1;
        }

        if (str.length() == 1){
            return 1;
        }

        // 最长子串的长度
        int max = 0;
        // 最长子串
        String temp = "";
        StringBuilder subString = new StringBuilder();
        // str.substring
        for (int i = 0; i < str.length(); i ++){
            // 判断当前字符是否在子串中存在
            String current = String.valueOf(str.charAt(i));
            int index = subString.indexOf(current);
            if (index >= 0){
                // 存在， 判断是不是最长的子串
                if (subString.length() > max){
                    max = subString.length();
                    temp = subString.toString();
                }
                // 将子串清空
                subString.delete(0, index + 1);
//                // 从重复的字符开始重新找
//                i = index;
                // 如果最长子串比剩余的字符长，后边的就没有意义了
                if (max >= str.length() - i + subString.length()){
                    break;
                }
            }
            // 把当前字符添加到子串中
            subString.append(current);
        }
        if (subString.length() > max) {
            max = subString.length();
            temp = subString.toString();
        }
        System.out.println(str + " 的最长子串是：" + temp);
        return max;
    }

    public static int maxSubString1(String str){
        if (str == null && str.isEmpty()){
            return -1;
        }

        if (str.length() == 1){
            return 1;
        }
        int max = 0;

        for (int i = 0 ; i < str.length(); i ++){
            StringBuilder sb = new StringBuilder(String.valueOf(str.charAt(i)));
            for (int j = i + 1; j < str.length(); j ++){
                String current = String.valueOf(str.charAt(i));
                int index = sb.indexOf(current);
                if (index >= 0){
                    if (sb.length() > max){
                        max = sb.length();
                    }
                    break;
                } else{
                    sb.append(current);
                }
            }
            if (sb.length() > max){
                max = sb.length();
            }
        }

        return max;
    }

}
